package Client.Component;

import Client.Util;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Scanner;

public class GameFrame extends JFrame {
    /*
        游戏主界面的Frame窗口
        根据游戏状态呈现不同的界面
            如果是猜方，需要有一个输入答案的地方，且不允许绘制图案
            如果是画方，应该提供清空图案按钮，以及一个显示答案的地方
     */
    public static String status = "DRAW";
    public WorkSpace workSpace;
    public String subject;
    public GameFrame() throws IOException, ClassNotFoundException {
        //初始化窗口设置
        initFrame();

        //初始化游戏状态
        initGame();
//        test();

        //布置窗口控件
        layoutFrame();


        this.setVisible(true);
    }

    /*
    更改Frame窗口的初始设置
     */
    private void initFrame(){
        this.setSize(1200, 1000);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
    }

    /*
        给窗口添加控件，并布局
         */
    private void layoutFrame(){
        System.out.println("正在渲染界面");
        //添加窗口主容器
        JPanel j = new JPanel();
        this.setContentPane(j);
        this.setLayout(null);

        //画板区
        workSpace = new WorkSpace();
        workSpace.setBounds(300, 100, 600, 500);

        if(status.equals("DRAW"))
        {
            //清空图案按钮， 还应该有一个答案的提示处
            System.out.println("绘制方绘制");
            JButton jb = getClearButton(workSpace);
            JButton unDoButton = getUndoButton(workSpace);
            JLabel ans = new JLabel(subject);
            ans.setFont(new Font("微软雅黑", Font.PLAIN, 20));
            ans.setBounds(550, 25, 300, 75);
            j.add(ans);
            j.add(jb);
            j.add(unDoButton);
        } else{
            System.out.println("猜测方绘制");
            //如果是猜方，此处应该是答案输入处, 且有一个提交答案按钮
            JTextField ansInput = new JTextField();
            JButton commit = new JButton("提交答案");
            ansInput.setBounds(450, 650, 250, 50);
            commit.setBounds(530, 750, 85, 25);
            commit.addActionListener(e -> {
                String ans = ansInput.getText();
                ArrayList<Object> command = new ArrayList<>();
                command.add("提交答案");
                command.add(ans);
                try {
                    sendCommand(command);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            });
            j.add(ansInput);
            j.add(commit);
        }

        j.add(workSpace);
    }

    /*
    绘制方函数
     */
    //绘制用：清空画板按钮
    private static JButton getClearButton(WorkSpace workSpace) {
        JButton jb = new JButton("清空画板");
        jb.setBounds(600, 650, 85, 25);
        jb.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                //清空点集，清空画笔颜色集合
                super.mouseClicked(e);
                workSpace.getDrawPanel().getLists().clear();
                workSpace.getDrawPanel().setDrawTime(0);
                workSpace.getDrawPanel().getLineColors().clear();
                workSpace.repaint();
            }
        });
        return jb;
    }

    //绘制用: 撤回一条线段
    private static JButton getUndoButton(WorkSpace workSpace){
        JButton unDoButton = new JButton("撤销");
        unDoButton.setBounds(500, 650, 85, 25);
        unDoButton.addActionListener(e -> {
            workSpace.getDrawPanel().getLists().remove(workSpace.getDrawPanel().getLists().size() - 1);
            workSpace.getDrawPanel().getLineColors().remove(workSpace.getDrawPanel().getLineColors().size() - 1);
            workSpace.getDrawPanel().setDrawTime(workSpace.getDrawPanel().getDrawTime() - 1);
            workSpace.repaint();
        });

        return unDoButton;
    }

    public void initGame() throws IOException, ClassNotFoundException {
        //从服务端获取身份
        System.out.println("游戏初始化");
        System.out.println("准备接受用户状态信息");
        ArrayList<Object> rec = new ArrayList<>();
        rec = (ArrayList<Object>) Util.ois.readObject();
        status = (String) rec.get(0);
        if(status.equals("DRAW"))
        {
            subject = (String) rec.get(1);
            System.out.println(subject);
        }

        System.out.println("已接收到用户状态信息");
        System.out.println(status);
//        status = "DRAW";
    }
    public void test(){
        System.out.println("Input please");
        Scanner sc = new Scanner(System.in);
        status = sc.next();
    }

    public void startGame() throws IOException, ClassNotFoundException {
        //猜测方则等待服务端的指令转发
        if(status.equals("GUESS")){
            System.out.println("猜测方业务逻辑");
            ArrayList<Object> command;
            while((command = (ArrayList<Object>) Util.ois.readObject()) != null && !Util.socket.isClosed()){
                String c = (String) command.get(0);
                System.out.println(c);
                if(c.contains("绘制")){
                    commandDraw(command);
                }
                else if(c.equals("提交答案")){
                    commandSubmit(command);
                }

            }
            JOptionPane.showMessageDialog(this, "服务器已关闭");
        }
        //登录后开启游戏，绘制方每次绘画动作时给服务端发送，并让服务端转发给其他客户端
        //该过程可以写在DrawPanel中的事件监听中
        else{
            System.out.println("绘制方业务逻辑");
            ArrayList<Object> command;
            while((command = (ArrayList<Object>) Util.ois.readObject()) != null && !Util.socket.isClosed()){
                String c = (String) command.get(0);
                System.out.println(c);
                if(c.equals("提交答案")){
                    commandSubmit(command);
                }
            }
        }
    }

    public void sendCommand(ArrayList<Object> command) throws IOException {
        System.out.println("准备发送数据");
        if(!Util.socket.isClosed()){
            Util.oos.writeObject(command);
        }
        else
            JOptionPane.showMessageDialog(this, "服务器已关闭");
    }

    public void commandDraw(ArrayList<Object> command){
        System.out.println("接收到绘制指令");
        workSpace.getDrawPanel().setDrawTime((int) command.get(1));
        workSpace.getDrawPanel().setLists((ArrayList<LinkedList<Point>>) command.get(2));
        workSpace.getDrawPanel().setLineColors((ArrayList<Color>) command.get(3));

        workSpace.getDrawPanel().repaint();
    }

    public void commandSubmit(ArrayList<Object> command){
        boolean flag = (boolean) command.get(1);
        if(flag){
            JOptionPane.showMessageDialog(this, "猜测方答案正确, 准备开启下一回合");
//                        nextRound();
        }
    }
}
